<script setup>
import { onMounted } from 'vue';
defineOptions({
    name: ''
})
const  extractTopLevels=(treeData, depth = 0, maxDepth = 3) =>{
  let result = [];

  treeData.forEach(node => {
    // 将当前节点添加到结果集中
    result.push(node);

    // 如果当前层级未达到最大深度，继续递归遍历子节点
    if (depth < maxDepth && node.children && node.children.length > 0) {
      // 递归提取子节点的前maxDepth-depth层数据
      result = result.concat(extractTopLevels(node.children, depth + 1, maxDepth));
    }
  });

  return result;
}
/**
 * @description 树形数据保留指定层级
 * @param data
 * @param level
 * @return {*[]|*}
 */
 const keepNodesAtLevel = (data, level) => {
  if (level == 1) {
    return data.map((node) => {
      return {
        value: node.value,
        label: node.label
      }
    })
  }
  let result = []
  for (let i = 0; i < data.length; i++) {
    let node = data[i]
    if (node.children) {
      node.children = keepNodesAtLevel(node.children, level - 1)
    }
    result.push(node)
  }
  return result
}

// 示例树形数据结构
const treeData = [
  {
    id: 1,
    label: "Level 1",
    children: [
      {
        id: 2,
        label: "Level 2",
        children: [
          {
            id: 3,
            label: "Level 3",
            children: [
              {
                id: 4,
                label: "Level 4",
                children: []
              }
            ]
          }
        ]
      }
    ]
  },
  // 可以有多个根节点
];


onMounted(()=>{

const arr = keepNodesAtLevel(treeData,3)
console.log(arr);
})
</script>

<template>
    <div>联合会员</div>
</template>

<style lang='scss' scoped>

</style>
